<template>
  <el-dialog
    custom-class="devSn-dialog"
    top="30px"
    :visible.sync="dialogVisible"
    width="1200px"
    title="选择机台"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :append-to-body="true"
    @closed="
      chose = [];
      equipList = [];
    "
    center
  >
    <el-row type="flex" justify="space-between">
      <el-col :span="12">
        <div class="mb10">已选机台：：{{ chose.length }}台</div>
        <div class="tag-list">
          <el-tag
            v-for="(tag, i) in tags"
            :key="i"
            size="small"
            closable
            @close="closeTag(tag, i)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </el-col>
      <el-col :span="8">
        <el-input
          size="small"
          v-model.trim="searchInput"
          placeholder="请输入机台号，如连号#1~#20"
        >
          <el-button
            type="primary"
            slot="append"
            size="small"
            style="background: #2c67f6; color: #fff"
            @click="textChose"
            >确定</el-button
          ></el-input
        >
      </el-col>
    </el-row>
    <div class="box mb10">
      <div class="content">
        <el-checkbox-group v-model="chose" class="grid" @change="toggleChose">
          <el-tooltip
            v-for="(item, i) in equipList"
            class="item"
            effect="dark"
            :content="`该机台已选人数为${item.devSelectedNumber}`"
            placement="top"
            :key="i"
          >
            <el-checkbox-button
              v-if="gongxu == '细纱'"
              :label="item.devSn"
              :class="{
                split: i == 24 || i == 60 || i == 96 || i == 132 || i == 168,
                wall: i == 24,
              }"
              :checked="item.status == '1'"
              :disabled="item.status == '2'"
              @mousedown.native="(e) => holdDown(e, item.status)"
              @mouseup.native="(e) => holdUp(e, item.status)"
              ><span v-html="splitNumber(item.devSn)"
            /></el-checkbox-button>
            <el-checkbox-button
              v-else
              :label="item.devSn"
              :checked="item.status == '1'"
              :disabled="item.status == '2'"
              @mousedown.native="(e) => holdDown(e, item.status)"
              @mouseup.native="(e) => holdUp(e, item.status)"
              ><span v-html="splitNumber(item.devSn)"
            /></el-checkbox-button>
          </el-tooltip>
        </el-checkbox-group>
      </div>
    </div>
    <el-row type="flex" justify="end">
      <el-button size="small" @click="dialogVisible = false">取消</el-button>
      <el-button size="small" type="primary" @click="confirmChoice"
        >确定</el-button
      >
    </el-row>
  </el-dialog>
</template>

<script>
import { getDevSn, getEquipNumber, editSchedule } from '@/api/dispatch';
export default {
  props: {
    date: {
      type: String,
    },
  },
  data() {
    return {
      gongxu: '',
      pz: '',
      row: {},
      dialogVisible: false,
      searchInput: '',
      equipList: [],
      tags: [],
      chose: [],
      nowClick: '',
      endClick: '',
    };
  },
  methods: {
    show(records, pz) {
      this.dialogVisible = true;
      this.row = Object.assign({}, records);
      this.gongxu = this.row.current_gongxu;
      this.pz = pz;
      this.chose = [];
      this.tags = [];
      this.$nextTick(() => {
        this.getDevSn();
      });
    },
    async getEquipNum() {
      const res = await getEquipNumber({ gongxu: this.row.current_gongxu });
      if (res.code == 1) {
        let { data } = res;
        // 粗纱会出现多个设备号 具体还要在看
        let equip = data[0]['equipment'];
        this.getDevSn(equip);
      }
    },
    async getDevSn() {
      let query = {
        time: this.date,
        gongxu: this.row.current_gongxu,
        pz: this.pz,
      };
      let params = Object.assign({}, this.row);
      params = this.$_.pick(params, [
        'cj',
        'bc',
        'current_work_type',
        'gh',
        'org',
      ]);
      query = Object.assign(query, params);
      const res = await getDevSn(query);
      if (res.code == 1) {
        this.equipList = res.data;
        setTimeout(() => {
          this.$nextTick(() => {
            this.toggleChose(this.chose);
          });
        });
      }
    },
    async confirmChoice() {
      let devSnArr = [...new Set(this.chose)];
      let params = this.$_.pick(this.row, [
        'cj',
        'current_work_type',
        'gh',
        'bc',
        'id',
      ]);
      params = Object.assign(
        {
          pz: this.pz,
          gongxu: this.row.current_gongxu,
          time: this.date,
          checkedDev: devSnArr,
        },
        params
      );
      const res = await editSchedule(params);
      if (res.code == 1) {
        this.$message.success('操作成功');
        this.$emit('getData', this.row.current_work_type);
        this.dialogVisible = false;
      }
    },
    toggleChose(val) {
      if (val) {
        let arr = [].concat(val);
        arr.sort(function (a, b) {
          return a - b;
        });
        this.tags = this.getSeiresDevsn(arr);
      } else {
        this.tags = [];
      }
    },
    splitNumber(val) {
      if (val) {
        let arr = val.split('');
        val = arr.join('<br>');
        return val;
      }
    },
    textChose() {
      // 获取不连号数组
      let str = this.searchInput.substring(1);
      let arrSplit = str.split('~#');
      let arr = [parseInt(arrSplit[0]), parseInt(arrSplit[1])];
      let test = [];
      for (let i = 0; i < arr[1] - arr[0] - 1; i++) {
        test.push(arr[0] + 1 * (i + 1));
      }
      arr.splice(1, 0, ...test);
      // 去掉已有项
      let final = [];
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < this.chose.length; j++) {
          if (arr[i] == this.chose[j]) {
            arr[i] = '';
            break;
          }
        }
      }
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] != '') {
          final.push(String(arr[i]));
        }
      }
      final = final.filter((item) => {
        let flag = this.equipList.find((finditem) => {
          // 如果是禁选
          return finditem.devSn == item && finditem.status !== '2';
        });
        return flag;
      });
      this.chose.splice(0, 0, ...final);
      this.toggleChose(this.chose);
    },
    closeTag(val, index) {
      let str = val.substring(1);
      let arrSplit = str.split('~#');
      let arr = [parseInt(arrSplit[0]), parseInt(arrSplit[1])];
      let test = [];
      for (let i = 0; i < arr[1] - arr[0] - 1; i++) {
        test.push(arr[0] + 1 * (i + 1));
      }
      arr.splice(1, 0, ...test);
      // 去掉相同项
      let final = [];
      for (let i = 0; i < this.chose.length; i++) {
        for (let j = 0; j < arr.length; j++) {
          if (this.chose[i] == arr[j]) {
            this.chose[i] = '';
            break;
          }
        }
      }
      for (let i = 0; i < this.chose.length; i++) {
        if (this.chose[i] != '') {
          final.push(this.chose[i]);
        }
      }
      this.tags.splice(index, 1);
      this.chose = final;
    },
    // 获取连续车台
    getSeiresDevsn(arr) {
      var result = [],
        i = 0,
        str = [];
      if (arr.length > 0) {
        result[i] = [arr[0]];
        arr.reduce(function (prev, cur) {
          parseInt(cur) - parseInt(prev) === 1
            ? result[i].push(cur)
            : (result[++i] = [cur]);
          return cur;
        });
        result.map((item) => {
          if (item.length > 1) {
            str.push(`#${item[0]}~#${item[item.length - 1]}`);
          } else {
            str.push(`#${item[0]}`);
          }
        });
      } else {
        str = [];
      }
      return str;
    },
    holdDown(e, status) {
      if (status !== '2') {
        this.nowClick = e.target.innerText;
      }
    },
    holdUp(e, status) {
      if (this.nowClick == e.target.innerText || status == '2') {
        this.nowClick = null;
        return;
      } else {
        let endClick = e.target.innerText;
        endClick = parseInt(endClick.replaceAll('\n', ''));
        this.nowClick = parseInt(this.nowClick.replaceAll('\n', ''));
        let first = this.nowClick < endClick ? this.nowClick : endClick;
        let last = endClick > this.nowClick ? endClick : this.nowClick;
        let arr = [];
        for (let i = first; i <= last; i++) {
          arr.push(String(i));
        }
        let final = [].concat(this.chose);
        final.push(...arr);
        console.log(final);
        const set = new Set(final);
        console.log(set);
        this.chose = [...set];
        this.toggleChose(this.chose);
      }
    },
  },
};
</script>

<style lang="scss">
.devSn-dialog {
  .box {
    border: 1px solid #dee0e3;
    border-radius: 2px;
    overflow: auto;
    box-sizing: border-box;
    margin-top: 15px;
  }
  .tag-list {
    .el-tag + .el-tag {
      margin-left: 8px;
    }
  }
  .content {
    width: max-content;
    padding: 20px 10px;
    .grid {
      display: grid;
      grid-template-columns: repeat(37, 25px);
      grid-column-gap: 8px;
      grid-row-gap: 15px;
    }
    .split {
      grid-column: span 2;
    }
    .wall {
      position: relative;
      &:after {
        display: block;
        content: '';
        position: absolute;
        left: 41px;
        top: -21px;
        width: 5px;
        height: 499px;
        background: rgba(53, 65, 86, 0.5);
        border: 1px solid #354156;
      }
    }

    .el-checkbox-button {
      width: 25px;
      height: 80px;
      border-radius: 2px;
      .el-checkbox-button__inner {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        border: none;
        background: #f1f5f8;
        color: #4a576c;
        font-size: 16px;
        padding: 0;
        box-shadow: none;
      }
      &.is-checked {
        .el-checkbox-button__inner {
          background: #e1f0ff;
          color: #2c67f6;
        }
      }
      &.is-disabled {
        .el-checkbox-button__inner {
          background: #e3e3e3;
          color: rgba(74, 87, 108, 0.3);
        }
      }
    }
  }
}
</style>
